 ///
 /// @file    abstractClass.cc
 /// @author  lemon(haohb13@gmail.com)
 /// @date    2023-05-05 10:30:13
 ///
 
#include <string.h>

#include <iostream>
using std::cout;
using std::endl;

class Base {
public:
	Base(const char * pbase) 
	: _pbase(new char[strlen(pbase) + 1]())
	{	
		cout << "Base(const char*)" << endl;	
		strcpy(_pbase, pbase);
	}	

	virtual
	void display()  const 
	{	cout << "Base::display()" << endl;	}

	//注意：如果以后都希望基类指针可以释放派生类对象，
	//那么都要将析构函数设置为虚函数
	virtual
	~Base() {
		cout << "~Base()" << endl;
		if(_pbase) {
			delete [] _pbase;
			_pbase = nullptr;
		}
	}

private:
	char * _pbase;
};

class Derived
: public Base {
public:
	Derived(const char * pbase, const char * pderived)
	: Base(pbase)
	, _pderived(new char[strlen(pderived) + 1]())
	{	
		cout << "Derived(const char*, const char*)" << endl;	
		strcpy(_pderived, pderived);
	}

	~Derived()
	{
		cout << "~Derived()" << endl;
		if(_pderived) {
			delete [] _pderived;
			_pderived = nullptr;
		}
	}

private:
	char * _pderived;
};
 
void test0() 
{
	Base * pbase = new Derived("hello", "world");
	//delete (Derived*)pbase;
	delete pbase;//就希望通过该语句能释放派生类对象
} 
 
int main(void)
{
	test0();
	return 0;
}
